import {url} from '@/store/utils'
import {get} from 'lodash'
import FileUploader from '@/components/widgets/file_uploader/FileUploader.vue'

export interface FileUploadFileData {
  key: string,
  'x:upload_number': string
}

export interface FileUploadFile {
  fileObject: boolean,
  id: string | number,
  size: number,
  name: string,
  type: string,
  active: boolean,
  error: string,
  success: boolean,
  putAction: string,
  postAction: string,
  headers: object,
  data: FileUploadFileData,
  timeout: number,
  progress: string,
  speed: number,
  xhr: XMLHttpRequest,
  iframe: Element

}

const DURATION = 3000

async function doubleCheckUploadStatus(file: FileUploadFile, retry: number, instance: FileUploader) {

  let fileName = file.data.key
  let uploadNumber = file.data['x:upload_number']
  console.info(`检查后台文件上传状态 ${uploadNumber} | ${fileName}`)
  if (retry > 3) {
    // TODO mark timeout or other waring message to user
    console.warn(`检查文件上传状态超时 ${uploadNumber} | ${fileName}`)
    instance.$set(file, "warning", "文件效验超时，请不要重复上传")
    return
  }
  let response = await axios.post(url('/api/oss/check-file-status'), {
    'file_name': fileName, 'upload_number': uploadNumber
  })
  if (!get(response, 'data.result', false)) {
    // 未查到上传记录
    setTimeout(function () {
      doubleCheckUploadStatus(file, retry + 1, instance)
    }, 1000 * retry)
  } else {
    // 上传成功
    // console.info(`上传文件检查成功 ${fileName}`)
    instance.onFileUploadSuccess()
    instance.$refs.upload.remove(file)
  }
}


function onFileUpdate(newFile: FileUploadFile, oldFile: FileUploadFile, instance: FileUploader) {
  // 上传错误
  if (newFile.error !== oldFile.error) {
    // eslint-disable-next-line no-console
    console.log('error', newFile.error, newFile)
  }

  // 上传成功
  if (newFile.success !== oldFile.success) {
    console.info(`上传完成 ${newFile}`)
    // @ts-ignore
    doubleCheckUploadStatus(newFile, 1, instance)
    // console.log('success', newFile.success, newFile)
  }
}

function onAddNewFile(newFile: FileUploadFile, instance: FileUploader) {
}


function fileUploadEventHandler(newFile: FileUploadFile, oldFile: FileUploadFile, instance: FileUploader) {
  if (newFile && !oldFile) {
    onAddNewFile(newFile, instance)
  }
  if (newFile && oldFile) {
    onFileUpdate(newFile, oldFile, instance)
  }

}

export default fileUploadEventHandler